from django.db import transaction
from django.core.exceptions import ValidationError
from ..apps.warehouse.models import InboundOrder, Inventory

def approve_inbound_order(order_id: int):
    """
    审核入库单并更新库存
    - 使用事务保证原子性
    - select_for_update() 锁定记录防止并发冲突
    - 更新库存时使用 get_or_create 处理新老物料
    """
    try:
        with transaction.atomic():  # 开启事务
            # 锁定单据防止并发修改
            order = InboundOrder.objects.select_for_update().get(id=order_id)
            
            if order.status != 'pending':
                raise ValidationError("单据状态不是待审核")
            
            # 遍历明细更新库存
            for detail in order.details.all():
                # 获取或创建库存记录
                inventory, created = Inventory.objects.get_or_create(
                    warehouse=order.warehouse,
                    material=detail.material,
                    status='normal',
                    defaults={'quantity': detail.quantity}
                )
                
                if not created:
                    # 已有记录则累加数量
                    inventory.quantity += detail.quantity
                    inventory.save()
            
            # 更新单据状态
            order.status = 'approved'
            order.save()
            
            return True
    except InboundOrder.DoesNotExist:
        raise ValidationError("入库单不存在")